package dao.impl;

import DbHelper.DbHelper;
import dao.BookDao;
import entry.Book;



import java.util.ArrayList;

public class BookDaoImpl implements BookDao {
    DbHelper db = new DbHelper();

    @Override
    public int insert(Book book) {
        String sql = "insert into books(BOOKNAME,BOOKAUTHOR,BOOKPUBLISH,BOOKPAGE,BOOKPRICE,CREATEDATE) values( ? , ? , ?  ,?  , ? , current_date())";
        return db.updateDate(sql, book.getBOOKNAME(), book.getBOOKAUTHOR(), book.getBOOKPUBLISH(), book.getBOOKPAGE(), book.getBOOKPRICE());
    }

    @Override
    public ArrayList<Book> bookQuery() {
        String sql = "select * from books";
        return db.query(sql, Book.class);
    }

    @Override
    public ArrayList<Book> selectBook(Book book) {
        StringBuilder strb = new StringBuilder("select * from books   where 1=1 ");
        ArrayList<Book> list = new ArrayList<>();
        if (book.getBOOKNAME() != null) {
            strb.append("and bookname like ? ");
            return db.query(strb.toString(), Book.class, "%" + book.getBOOKNAME() + "%");
        }
        if (book.getBOOKAUTHOR() != null) {
            strb.append("and bookauthor=? ");
            return db.query(strb.toString(), Book.class, book.getBOOKAUTHOR());
        }
        if (book.getBOOKPUBLISH() != null) {
            strb.append("and bookpublish = ? ");
            return db.query(strb.toString(), Book.class, book.getBOOKPUBLISH());
        }
        return db.query(strb.toString(), list.getClass());
    }

    @Override
    public boolean deleteBook(int bid) {
        String sql="delete  from books where BOOKID=? ";
        return db.updateDate(sql,bid)>0?true:false;
    }

    @Override
    public Book selectBid(int bid) {
        String sql="select *from books where BOOKID=? ";
        return (Book)(db.query(sql, Book.class,bid).get(0));
    }

    @Override
    public boolean update(Book book) {
        String sql="update books set BOOKNAME=?, BOOKAUTHOR=?, BOOKPUBLISH=? , BOOKPAGE=?, BOOKPRICE=?, CREATEDATE=? where BOOKID=? ";
        Object[] objs={book.getBOOKNAME(),book.getBOOKAUTHOR(),book.getBOOKPUBLISH(),book.getBOOKPAGE(),book.getBOOKPRICE(),book.getCREATEDATE(),book.getBOOKID()};
        return db.updateDate(sql,objs)>0?true:false;
    }

}
